package com.ninghushangbao.ninghu.controller;

import com.ninghushangbao.ninghu.controller.vo.UpdatePasswordVo;
import com.ninghushangbao.ninghu.controller.vo.VerifyCode;
import com.ninghushangbao.ninghu.entity.User;
import com.ninghushangbao.ninghu.service.UserService;
import com.ninghushangbao.ninghu.utils.BaseJwtUtils.TokenUtil;
import com.ninghushangbao.ninghu.utils.BaseResult.ResultCodeEnum;
import com.ninghushangbao.ninghu.controller.vo.Loginvo;
import com.ninghushangbao.ninghu.controller.vo.ResultEntity;
import com.ninghushangbao.ninghu.utils.BaseResult.ResultUtil;
import com.ninghushangbao.ninghu.utils.MD5utils;
import com.ninghushangbao.ninghu.utils.VerifyUtils.IVerifyCodeGen;
import com.ninghushangbao.ninghu.utils.VerifyUtils.SimpleCharVerifyCodeGenImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
//@CrossOrigin()
public class AdminController {

    @Autowired
    UserService userService;
    /*
    * 存储token
    * */
    public static Map<String,String> tokenMap = new HashMap<>();
    /*
     * 获取验证码
     * */
    @GetMapping("/captcha/get")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 40);
            String code = verifyCode.getCode();
            //LOGGER.info(code);
            //将VerifyCode绑定session
            for (Cookie c : request.getCookies() != null ? request.getCookies() : new Cookie[0]) {
                System.out.println(c.getName() + "=" + c.getValue());
            }
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        }
        catch (IOException e) {
            //LOGGER.info("", e);
        }
    }

    /*
     * 登陆验证
     * */
    @PostMapping("/login")
    public ResultEntity login(@RequestBody Loginvo loginvo, HttpServletRequest request, HttpServletResponse response) {

        System.out.println(loginvo);
        //接收验证码
        String verifyCode = loginvo.getCheckcode();
        String code = (String) request.getSession().getAttribute("VerifyCode");
        System.out.println("code=" + code);

        System.out.println("verifyCode=" + verifyCode);
        if (StringUtils.isEmpty(verifyCode) || !verifyCode.equals(code)) {
            return ResultUtil.error(ResultCodeEnum.VERIFY_CODE_ERROR.getCode(), ResultCodeEnum.VERIFY_CODE_ERROR.getMsg());
        }
        //验证用户名和密码
        String username = loginvo.getUsername();
        MD5utils md5utils = new MD5utils();
        String password = md5utils.EncoderByMd5(loginvo.getPassword());
        //String password = loginvo.getPassword();

        List<User> users = userService.getUsers();

        for (User user: users) {
            if(username.equals(user.getUserName())&&password.equals(user.getPassword())){
                /*
                * 验证成功加入token
                * */
                User user1 = userService.getUserByUserName(user);
                tokenMap.put(String.valueOf(user1.getUserId()), TokenUtil.getToken(String.valueOf(user1.getUserId()))) ;
                return ResultUtil.success(TokenUtil.getToken(String.valueOf(user1.getUserId())));
            }
            if(username.equals(user.getUserName())&&(!password.equals(user.getPassword()))){
                return ResultUtil.error(ResultCodeEnum.PASSWORD_ERROR);
            }
            if(password.equals(user.getPassword())&&(!username.equals(user.getUserName()))){
                return ResultUtil.error(ResultCodeEnum.USERNAME_ERROR);
            }
        }
        return ResultUtil.success();
    }

    /*
     * 查询后台展示用户
     * */
    @GetMapping("/sel_all")
    public ResultEntity selectAllUser() {
        return ResultUtil.success(userService.getUserVo());
    }
    /*
     * 删除用户
     * */
    @DeleteMapping("/user_del")
    public ResultEntity userDel(@RequestBody List<Integer> listId) {
        System.out.println("----------------------");
        for (Integer integer:listId) {
            System.out.println((int)integer);
        }
        userService.deleteUsersById(listId);
        return ResultUtil.success();
    }
    /*
     * 修改用户
     * */
    @PutMapping("/user_mod")
    public ResultEntity userMod(@RequestBody User user) {
        userService.updateUser(user);
        return ResultUtil.success();
    }
    /*
    * 新增用户
    * */
    @PostMapping("/user_add")
    public ResultEntity userAdd(@RequestBody User user){
        MD5utils md5utils = new MD5utils();
        user.setPassword(md5utils.EncoderByMd5(user.getPassword()));
        userService.addUser(user);
        return ResultUtil.success();
    }
    /*
    * 修改密码
    * */
    @PostMapping("/update_password")
    public ResultEntity updatePassword(@RequestBody UpdatePasswordVo updatePasswordVo){
        System.out.println(updatePasswordVo.getUserId());
        System.out.println(updatePasswordVo.getOldPassword());
        System.out.println(updatePasswordVo.getNewPassword());

        String password = userService.getUserById(updatePasswordVo.getUserId()).getPassword();
        MD5utils md5utils =new MD5utils();
        String oldPassword = md5utils.EncoderByMd5(updatePasswordVo.getOldPassword());
        //String oldPassword = updatePasswordVo.getOldPassword();
        if(!oldPassword.equals(password)){
            return ResultUtil.error(ResultCodeEnum.PASSWORD_ERROR);
        }
        User user = new User();
        user.setUserId(updatePasswordVo.getUserId());
        user.setPassword(md5utils.EncoderByMd5(updatePasswordVo.getNewPassword()));
        userService.updatePasswordById(user);
        return ResultUtil.success();
    }
    /*
    * 通过用户名查询用户信息
    * */
    @GetMapping("/sel_user")
    public ResultEntity selectUserByUserName(@RequestParam("userName") String username){
        User user = new User();
        user.setUserName(username);
        return ResultUtil.success(userService.getUserByUserName(user));
    }
    /*
    * 退出登录接口
    * */
    @GetMapping("/out_login")
    public ResultEntity outLogin(){
        tokenMap.clear();
        return ResultUtil.success(ResultCodeEnum.OUT_LOGIN_ERROR);
    }
}
